import Koa from "koa";
import { koaBody } from "koa-body";
import serve from "koa-static";
import mount from "koa-mount";
import Router from "koa-router";
import parameter from "koa-parameter";
import { fileURLToPath } from "url";
import { dirname, join } from "path";

const indexRouter = new Router();

import router from "../router/index.js";
import { processError } from "./errHandler.js";
const app = new Koa();
app.use(
  koaBody({
    multipart: true,
    formidable: {
      uploadDir: "./src/upload",
      keepExtensions: true, // Keep the original file extension 保持文件后缀
      //   maxFileSize: 200 * 1024 * 1024,
    },
  })
);
const __dirname = dirname(fileURLToPath(import.meta.url));
// 引用上一级目录中的 public 文件夹
const publicPath = join(__dirname, "..", "public");
const uploadPath = join(__dirname, "..", "upload");
// 静态资源目录配置
app.use(mount("/upload", serve(uploadPath)));
app.use(mount("/public", serve(publicPath)));

app.use(parameter(app));
// 读取HTML文件

router.get("/", (ctx) => {
  ctx.redirect("/public/index.html");
});
app.use(router.routes()); // Use the user router
app.use(router.allowedMethods());
app.on("error", processError);

app.use(indexRouter.routes());
export default app;
